// New tab page script
let currentSection = 'reminders';
let currentFilter = 'all';
let achievementFilter = 'all';
let longevityContent = [];
let userContent = [];
let favorites = [];
let reminders = [];
let goals = [];
let achievements = [];
let gamificationData = null;

// Background noise player
let audioContext = null;
let currentNoise = null;
let noiseNodes = [];
let noiseVolume = 0.5;
let noiseIntervals = [];

// Initialize on load
document.addEventListener('DOMContentLoaded', async () => {
  await initialize();
  setupEventListeners();
  loadSection(currentSection);
});

async function initialize() {
  // Initialize storage
  await StorageManager.initialize();
  
  // Load default reminders if first run
  const data = await chrome.storage.local.get(['reminders', 'initialized', 'settings']);
  if (!data.reminders || data.reminders.length === 0) {
    if (typeof DEFAULT_REMINDERS !== 'undefined') {
      const remindersWithDefaults = DEFAULT_REMINDERS.map(r => ({
        ...r,
        lastTriggered: null
      }));
      await chrome.storage.local.set({ reminders: remindersWithDefaults });
      reminders = remindersWithDefaults;
    } else {
      reminders = [];
    }
  } else {
    reminders = data.reminders;
  }
  
  // Load longevity content
  if (typeof LONGEVITY_CONTENT !== 'undefined') {
    longevityContent = LONGEVITY_CONTENT;
  }
  
  // Load user content and favorites
  userContent = await StorageManager.getUserContent();
  favorites = await StorageManager.getFavorites();
  
  // Load settings
  const settings = await StorageManager.getSettings();
  const themeSelect = document.getElementById('themeSelect');
  const soundSelect = document.getElementById('soundSelect');
  const notificationsEnabled = document.getElementById('notificationsEnabled');
  const badgeEnabled = document.getElementById('badgeEnabled');
  
  if (themeSelect) themeSelect.value = settings.theme || 'light';
  if (soundSelect) soundSelect.value = settings.notificationSound || 'beep';
  if (notificationsEnabled) notificationsEnabled.checked = settings.notificationsEnabled !== false;
  if (badgeEnabled) badgeEnabled.checked = settings.badgeEnabled !== false;
  applyTheme(settings.theme || 'light');
  
  // Load background noise settings
  const noiseSettings = await StorageManager.getNoiseSettings();
  noiseVolume = noiseSettings.volume || 0.5;
  const volumeSlider = document.getElementById('noiseVolume');
  const volumeValue = document.getElementById('volumeValue');
  if (volumeSlider) {
    volumeSlider.value = noiseVolume * 100;
    if (volumeValue) volumeValue.textContent = Math.round(noiseVolume * 100) + '%';
  }
  
  // Initialize audio context
  if (typeof AudioContext !== 'undefined' || typeof webkitAudioContext !== 'undefined') {
    audioContext = new (AudioContext || webkitAudioContext)();
  }
  
  // Load gamification data
  await loadGamificationData();
  
  // Initialize default goals if first run
  const userGoals = await StorageManager.getGoals();
  if (userGoals.length === 0 && typeof DEFAULT_GOALS !== 'undefined') {
    for (const goal of DEFAULT_GOALS) {
      await StorageManager.addGoal(goal);
    }
  }
  goals = await StorageManager.getGoals();
  
  // Load achievements
  if (typeof ACHIEVEMENTS !== 'undefined') {
    achievements = ACHIEVEMENTS;
  }
  
  // Clear badge when new tab opens
  chrome.runtime.sendMessage({ action: 'clearBadge' });
  chrome.action.setBadgeText({ text: '' });
}

async function loadGamificationData() {
  gamificationData = await StorageManager.getGamificationData();
  await StorageManager.updateStreak(); // Update streak on load
  gamificationData = await StorageManager.getGamificationData();
  updateGamificationUI();
  checkAchievements();
}

function setupEventListeners() {
  // Navigation
  document.querySelectorAll('.nav-item').forEach(item => {
    item.addEventListener('click', (e) => {
      e.preventDefault();
      const section = item.dataset.section;
      switchSection(section);
    });
  });
  
  // Filter buttons
  document.querySelectorAll('.filter-btn').forEach(btn => {
    btn.addEventListener('click', (e) => {
      document.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('active'));
      e.target.classList.add('active');
      currentFilter = e.target.dataset.filter;
      renderContent();
    });
  });
  
  // Add content form
  document.getElementById('addContentForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    const title = document.getElementById('contentTitle').value;
    const link = document.getElementById('contentLink').value;
    const description = document.getElementById('contentDescription').value;
    const category = document.getElementById('contentCategory').value;
    
    await StorageManager.addUserContent({ title, link, description, category });
    document.getElementById('addContentForm').reset();
    await initialize();
    switchSection('content');
  });
  
  // Add reminder button
  document.getElementById('addReminderBtn').addEventListener('click', () => {
    document.getElementById('addReminderModal').style.display = 'block';
  });
  
  // Add reminder form
  document.getElementById('addReminderForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    const title = document.getElementById('reminderTitle').value;
    const description = document.getElementById('reminderDescription').value;
    const frequency = parseInt(document.getElementById('reminderFrequency').value);
    const enabled = document.getElementById('reminderEnabled').checked;
    
    await StorageManager.addCustomReminder({ title, description, frequency, enabled });
    document.getElementById('addReminderModal').style.display = 'none';
    document.getElementById('addReminderForm').reset();
    await initialize();
    switchSection('reminders');
  });
  
  // Modal close buttons
  document.querySelectorAll('.close').forEach(closeBtn => {
    closeBtn.addEventListener('click', (e) => {
      e.target.closest('.modal').style.display = 'none';
    });
  });
  
  // Click outside modal to close
  window.addEventListener('click', (e) => {
    if (e.target.classList.contains('modal')) {
      e.target.style.display = 'none';
    }
  });
  
  // Settings event listeners
  const themeSelect = document.getElementById('themeSelect');
  const soundSelect = document.getElementById('soundSelect');
  const notificationsEnabled = document.getElementById('notificationsEnabled');
  const badgeEnabled = document.getElementById('badgeEnabled');

  if (themeSelect) {
    themeSelect.addEventListener('change', async (e) => {
      const theme = e.target.value;
      await StorageManager.updateSettings({ theme });
      applyTheme(theme);
    });
  }

  if (soundSelect) {
    soundSelect.addEventListener('change', async (e) => {
      const notificationSound = e.target.value;
      await StorageManager.updateSettings({ notificationSound });
    });
  }

  if (notificationsEnabled) {
    notificationsEnabled.addEventListener('change', async (e) => {
      await StorageManager.updateSettings({ notificationsEnabled: e.target.checked });
    });
  }
  
  if (badgeEnabled) {
    badgeEnabled.addEventListener('change', async (e) => {
      await StorageManager.updateSettings({ badgeEnabled: e.target.checked });
    });
  }
  
  // Clear badge button
  document.getElementById('clearBadge').addEventListener('click', () => {
    chrome.action.setBadgeText({ text: '' });
    chrome.storage.local.set({ badgeCount: 0 });
  });
  
  // Add goal button
  document.getElementById('addGoalBtn').addEventListener('click', () => {
    document.getElementById('addGoalModal').style.display = 'block';
  });
  
  // Add goal form
  document.getElementById('addGoalForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    const title = document.getElementById('goalTitle').value;
    const description = document.getElementById('goalDescription').value;
    const target = parseInt(document.getElementById('goalTarget').value);
    const unit = document.getElementById('goalUnit').value;
    const category = document.getElementById('goalCategory').value;
    const type = document.getElementById('goalType').value;
    
    await StorageManager.addGoal({
      title,
      description,
      target,
      unit,
      category,
      type,
      xpReward: target * 10, // Base XP reward
      resetFrequency: type === 'daily' ? 'daily' : type === 'weekly' ? 'weekly' : 'never'
    });
    
    document.getElementById('addGoalModal').style.display = 'none';
    document.getElementById('addGoalForm').reset();
    goals = await StorageManager.getGoals();
    if (currentSection === 'goals') {
      renderGoals();
    }
  });
  
  // Achievement filter buttons
  document.querySelectorAll('.achievement-filter .filter-btn').forEach(btn => {
    btn.addEventListener('click', (e) => {
      document.querySelectorAll('.achievement-filter .filter-btn').forEach(b => b.classList.remove('active'));
      e.target.classList.add('active');
      achievementFilter = e.target.dataset.filter;
      renderAchievements();
    });
  });
  
  // Background noise volume control
  const volumeSlider = document.getElementById('noiseVolume');
  const volumeValue = document.getElementById('volumeValue');
  if (volumeSlider && volumeValue) {
    volumeSlider.addEventListener('input', async (e) => {
      noiseVolume = e.target.value / 100;
      volumeValue.textContent = e.target.value + '%';
      if (currentNoise) {
        updateNoiseVolume();
      }
      await StorageManager.updateNoiseSettings({ volume: noiseVolume });
    });
  }
  
  // Background noise play buttons
  document.querySelectorAll('.noise-play-btn').forEach(btn => {
    btn.addEventListener('click', async (e) => {
      const sound = e.target.closest('.noise-play-btn').dataset.sound;
      await toggleNoise(sound);
    });
  });
}

function switchSection(section) {
  currentSection = section;
  
  // Update nav items
  document.querySelectorAll('.nav-item').forEach(item => {
    item.classList.remove('active');
    if (item.dataset.section === section) {
      item.classList.add('active');
    }
  });
  
  // Update sections
  document.querySelectorAll('.section').forEach(sec => {
    sec.classList.remove('active');
  });
  document.getElementById(`${section}-section`).classList.add('active');
  
  loadSection(section);
}

function loadSection(section) {
  switch(section) {
    case 'content':
      renderContent();
      break;
    case 'reminders':
      renderReminders();
      break;
    case 'favorites':
      renderFavorites();
      break;
    case 'goals':
      renderGoals();
      break;
    case 'achievements':
      renderAchievements();
      break;
    case 'background-noise':
      initializeBackgroundNoise();
      break;
  }
}

function renderContent() {
  const container = document.getElementById('content-grid');
  let allContent = [...longevityContent, ...userContent];
  
  // Apply filter
  if (currentFilter !== 'all') {
    allContent = allContent.filter(item => item.category === currentFilter);
  }
  
  if (allContent.length === 0) {
    container.innerHTML = '<div class="empty-state"><p>No content available. Add some longevity information!</p></div>';
    return;
  }
  
  container.innerHTML = allContent.map(item => createContentCard(item)).join('');
  
  // Add favorite button listeners
  container.querySelectorAll('.favorite-btn').forEach(btn => {
    btn.addEventListener('click', async (e) => {
      e.stopPropagation();
      const id = btn.dataset.id;
      const isFavorite = await StorageManager.isFavorite(id);
      
      if (isFavorite) {
        await StorageManager.removeFavorite(id);
      } else {
        await StorageManager.addFavorite(id);
      }
      
      favorites = await StorageManager.getFavorites();
      renderContent();
      if (currentSection === 'favorites') {
        renderFavorites();
      }
    });
  });
  
  // Add click listeners to open links
  container.querySelectorAll('.content-card').forEach(card => {
    card.addEventListener('click', async (e) => {
      if (!e.target.classList.contains('favorite-btn')) {
        const link = card.dataset.link;
        if (link && link !== '#') {
          // Track article reading for gamification
          await trackArticleRead();
          chrome.tabs.create({ url: link });
        }
      }
    });
  });
}

async function trackArticleRead() {
  try {
    const gamificationData = await StorageManager.getGamificationData();
    const stats = gamificationData.stats || {};
    stats.articlesRead = (stats.articlesRead || 0) + 1;
    
    await StorageManager.updateGamificationData({ stats });
    
    // Update content reader goal progress
    const goals = await StorageManager.getGoals();
    const readerGoal = goals.find(g => g.id === 'content-reader');
    if (readerGoal) {
      await StorageManager.updateGoalProgress('content-reader', 1);
      gamificationData.goalProgress = (await StorageManager.getGamificationData()).goalProgress;
      
      const progress = gamificationData.goalProgress?.['content-reader'] || 0;
      if (progress >= readerGoal.target) {
        const { leveledUp, newLevel } = await StorageManager.completeGoal('content-reader', readerGoal.xpReward);
        if (leveledUp) {
          showLevelUpNotification(newLevel);
        }
      }
    }
    
    gamificationData = await StorageManager.getGamificationData();
    updateGamificationUI();
    checkAchievements();
  } catch (error) {
    console.error('Error tracking article read:', error);
  }
}

function renderFavorites() {
  const container = document.getElementById('favorites-grid');
  const allContent = [...longevityContent, ...userContent];
  const favoriteItems = allContent.filter(item => favorites.includes(item.id));
  
  if (favoriteItems.length === 0) {
    container.innerHTML = '<div class="empty-state"><p>No favorites yet. Star items to add them here!</p></div>';
    return;
  }
  
  container.innerHTML = favoriteItems.map(item => createContentCard(item)).join('');
  
  // Add favorite button listeners
  container.querySelectorAll('.favorite-btn').forEach(btn => {
    btn.addEventListener('click', async (e) => {
      e.stopPropagation();
      const id = btn.dataset.id;
      await StorageManager.removeFavorite(id);
      favorites = await StorageManager.getFavorites();
      renderFavorites();
    });
  });
  
  // Add click listeners
  container.querySelectorAll('.content-card').forEach(card => {
    card.addEventListener('click', async (e) => {
      if (!e.target.classList.contains('favorite-btn')) {
        const link = card.dataset.link;
        if (link && link !== '#') {
          // Track article reading for gamification
          await trackArticleRead();
          chrome.tabs.create({ url: link });
        }
      }
    });
  });
}

function renderReminders() {
  const container = document.getElementById('reminders-grid');
  
  if (reminders.length === 0) {
    container.innerHTML = '<div class="empty-state"><p>No reminders configured. Add one to get started!</p></div>';
    return;
  }
  
  container.innerHTML = reminders.map(reminder => createReminderCard(reminder)).join('');
  
  // Add toggle listeners
  container.querySelectorAll('.reminder-toggle').forEach(toggle => {
    toggle.addEventListener('change', async (e) => {
      const reminderId = e.target.dataset.id;
      const enabled = e.target.checked;
      await StorageManager.updateReminder(reminderId, { enabled });
      reminders = await StorageManager.getReminders();
      renderReminders();
    });
  });
}

function createContentCard(item) {
  const isFavorite = favorites.includes(item.id);
  const link = item.link || (item.references && item.references[0]?.url) || '#';
  
  return `
    <div class="content-card" data-link="${link}">
      <h3>
        ${item.title}
        <button class="favorite-btn ${isFavorite ? 'active' : ''}" data-id="${item.id}">
          ${isFavorite ? '⭐' : '☆'}
        </button>
      </h3>
      <span class="category">${item.category || 'General'}</span>
      <p>${item.description || ''}</p>
      ${item.references ? `
        <div class="references">
          <strong>Scientific References:</strong>
          ${item.references.map(ref => `
            <a href="${ref.url}" target="_blank" onclick="event.stopPropagation()">${ref.text}</a>
          `).join('')}
        </div>
      ` : ''}
    </div>
  `;
}

function createReminderCard(reminder) {
  const frequencyText = reminder.frequency >= 1440 
    ? 'Daily' 
    : reminder.frequency >= 60 
      ? `Every ${reminder.frequency / 60} hours` 
      : `Every ${reminder.frequency} minutes`;
  
  return `
    <div class="reminder-card">
      <div>
        <h3>
          <span class="reminder-icon">${reminder.icon || '⏰'}</span>
          ${reminder.title}
        </h3>
        <p>${reminder.description || ''}</p>
      </div>
      <div class="reminder-meta">
        <span class="frequency">${frequencyText}</span>
        <label class="toggle-switch">
          <input type="checkbox" class="reminder-toggle" data-id="${reminder.id}" ${reminder.enabled ? 'checked' : ''}>
          <span class="toggle-slider"></span>
        </label>
      </div>
    </div>
  `;
}

// Gamification functions
function updateGamificationUI() {
  if (!gamificationData) return;
  
  // Update stats dashboard
  document.getElementById('userLevel').textContent = gamificationData.level || 1;
  document.getElementById('currentStreak').textContent = gamificationData.currentStreak || 0;
  document.getElementById('totalXP').textContent = gamificationData.totalXP || 0;
  document.getElementById('goalsCompleted').textContent = gamificationData.stats?.goalsCompleted || 0;
  
  // Update XP progress bar
  const currentLevel = gamificationData.level || 1;
  const nextLevel = currentLevel + 1;
  const currentLevelXP = getTotalXPForLevel(currentLevel - 1);
  const nextLevelXP = getTotalXPForLevel(currentLevel);
  const currentXP = gamificationData.totalXP || 0;
  const progressXP = currentXP - currentLevelXP;
  const requiredXP = Math.max(nextLevelXP - currentLevelXP, 1);
  const progressPercent = Math.min((progressXP / requiredXP) * 100, 100);
  
  document.getElementById('xpProgressFill').style.width = `${progressPercent}%`;
  document.getElementById('xpProgressText').textContent = `${progressXP} / ${requiredXP} XP`;
  document.getElementById('currentLevelDisplay').textContent = currentLevel;
  document.getElementById('nextLevelDisplay').textContent = nextLevel;
}

function getTotalXPForLevel(level) {
  if (level <= 0) return 0;
  let total = 0;
  for (let i = 1; i <= level; i++) {
    total += Math.floor(100 * Math.pow(i, 1.5));
  }
  return total;
}

function renderGoals() {
  const container = document.getElementById('goals-grid');
  
  if (goals.length === 0) {
    container.innerHTML = '<div class="empty-state"><p>No goals set. Add a goal to start tracking your progress!</p></div>';
    return;
  }
  
  container.innerHTML = goals.map(goal => createGoalCard(goal)).join('');
  
  // Add progress update listeners
  container.querySelectorAll('.btn-progress').forEach(btn => {
    btn.addEventListener('click', async (e) => {
      const goalId = btn.dataset.id;
      const increment = parseInt(btn.dataset.increment || 1);
      await updateGoalProgress(goalId, increment);
    });
  });
  
  // Add delete listeners
  container.querySelectorAll('.btn-delete-goal').forEach(btn => {
    btn.addEventListener('click', async (e) => {
      const goalId = btn.dataset.id;
      if (confirm('Are you sure you want to delete this goal?')) {
        await StorageManager.removeGoal(goalId);
        goals = await StorageManager.getGoals();
        renderGoals();
      }
    });
  });
}

function createGoalCard(goal) {
  const progress = gamificationData?.goalProgress?.[goal.id] || 0;
  const isCompleted = progress >= goal.target;
  const progressPercent = Math.min((progress / goal.target) * 100, 100);
  
  return `
    <div class="goal-card ${isCompleted ? 'completed' : ''}">
      <div class="goal-card-header">
        <div class="goal-card-title">
          <span class="goal-card-icon">${goal.icon || '🎯'}</span>
          <span>${goal.title}</span>
        </div>
      </div>
      <div class="goal-card-description">${goal.description || ''}</div>
      <div class="goal-progress-container">
        <div class="goal-progress-header">
          <span>${progress} / ${goal.target} ${goal.unit || 'times'}</span>
          <span>${Math.round(progressPercent)}%</span>
        </div>
        <div class="goal-progress-bar">
          <div class="goal-progress-fill" style="width: ${progressPercent}%"></div>
        </div>
      </div>
      <div class="goal-card-footer">
        <span class="goal-xp-reward">+${goal.xpReward || 0} XP</span>
        <div class="goal-actions">
          <button class="btn-small btn-success btn-progress" data-id="${goal.id}" data-increment="1">
            +1
          </button>
          ${goal.target > 1 ? `
            <button class="btn-small btn-success btn-progress" data-id="${goal.id}" data-increment="5">
              +5
            </button>
          ` : ''}
          <button class="btn-small btn-danger btn-delete-goal" data-id="${goal.id}">
            Delete
          </button>
        </div>
      </div>
    </div>
  `;
}

async function updateGoalProgress(goalId, increment) {
  const goal = goals.find(g => g.id === goalId);
  if (!goal) return;
  
  const newProgress = await StorageManager.updateGoalProgress(goalId, increment);
  gamificationData = await StorageManager.getGamificationData();
  
  // Check if goal is completed
  if (newProgress >= goal.target) {
    const { leveledUp, newLevel, xpReward } = await StorageManager.completeGoal(goalId, goal.xpReward || 0);
    gamificationData = await StorageManager.getGamificationData();
    
    if (leveledUp) {
      showLevelUpNotification(newLevel);
    }
    
    if (xpReward > 0) {
      showXPNotification(xpReward);
    }
  }
  
  updateGamificationUI();
  renderGoals();
  checkAchievements();
}

function renderAchievements() {
  const container = document.getElementById('achievements-grid');
  
  if (achievements.length === 0) {
    container.innerHTML = '<div class="empty-state"><p>No achievements available.</p></div>';
    return;
  }
  
  const unlockedIds = gamificationData?.unlockedAchievements || [];
  let filteredAchievements = achievements;
  
  if (achievementFilter === 'unlocked') {
    filteredAchievements = achievements.filter(a => unlockedIds.includes(a.id));
  } else if (achievementFilter === 'locked') {
    filteredAchievements = achievements.filter(a => !unlockedIds.includes(a.id));
  }
  
  container.innerHTML = filteredAchievements.map(achievement => {
    const isUnlocked = unlockedIds.includes(achievement.id);
    return createAchievementCard(achievement, isUnlocked);
  }).join('');
}

function createAchievementCard(achievement, isUnlocked) {
  return `
    <div class="achievement-card ${isUnlocked ? 'unlocked' : 'locked'}">
      ${!isUnlocked ? '<span class="achievement-lock-icon">🔒</span>' : ''}
      <span class="achievement-icon">${achievement.icon}</span>
      <div class="achievement-title">${achievement.title}</div>
      <div class="achievement-description">${achievement.description}</div>
      <div class="achievement-rarity ${achievement.rarity}">${achievement.rarity}</div>
      <div class="achievement-xp">+${achievement.xpReward} XP</div>
    </div>
  `;
}

async function checkAchievements() {
  if (!gamificationData || typeof ACHIEVEMENTS === 'undefined') return;
  
  const unlockedIds = gamificationData.unlockedAchievements || [];
  const stats = gamificationData.stats || {};
  
  for (const achievement of ACHIEVEMENTS) {
    if (unlockedIds.includes(achievement.id)) continue;
    
    let shouldUnlock = false;
    const condition = achievement.condition;
    
    switch (condition.type) {
      case 'goals_completed':
        shouldUnlock = (stats.goalsCompleted || 0) >= condition.value;
        break;
      case 'streak':
        shouldUnlock = (gamificationData.currentStreak || 0) >= condition.value;
        break;
      case 'level':
        shouldUnlock = (gamificationData.level || 1) >= condition.value;
        break;
      case 'articles_read':
        shouldUnlock = (stats.articlesRead || 0) >= condition.value;
        break;
      case 'hydration_completed':
        shouldUnlock = (stats.hydrationCompleted || 0) >= condition.value;
        break;
      case 'achievements_unlocked':
        shouldUnlock = unlockedIds.length >= condition.value;
        break;
    }
    
    if (shouldUnlock) {
      const unlocked = await StorageManager.unlockAchievement(achievement.id);
      if (unlocked) {
        const { leveledUp, newLevel } = await StorageManager.addXP(achievement.xpReward);
        gamificationData = await StorageManager.getGamificationData();
        
        showAchievementNotification(achievement);
        
        if (leveledUp) {
          setTimeout(() => showLevelUpNotification(newLevel), 1500);
        }
        
        updateGamificationUI();
        renderAchievements();
      }
    }
  }
}

function showLevelUpNotification(level) {
  const notification = document.createElement('div');
  notification.className = 'level-up-notification';
  notification.innerHTML = `
    <div style="font-size: 24px; font-weight: 700; margin-bottom: 8px;">🎉 Level Up!</div>
    <div>You've reached level ${level}!</div>
  `;
  document.body.appendChild(notification);
  
  setTimeout(() => {
    notification.style.animation = 'slideIn 0.3s ease reverse';
    setTimeout(() => notification.remove(), 300);
  }, 3000);
}

function showAchievementNotification(achievement) {
  const notification = document.createElement('div');
  notification.className = 'achievement-unlock-notification';
  notification.innerHTML = `
    <div style="font-size: 24px; margin-bottom: 8px;">${achievement.icon}</div>
    <div style="font-weight: 700; margin-bottom: 4px;">Achievement Unlocked!</div>
    <div style="font-size: 14px;">${achievement.title}</div>
    <div style="font-size: 12px; margin-top: 4px; opacity: 0.8;">+${achievement.xpReward} XP</div>
  `;
  document.body.appendChild(notification);
  
  setTimeout(() => {
    notification.style.animation = 'slideIn 0.3s ease reverse';
    setTimeout(() => notification.remove(), 300);
  }, 3000);
}

function showXPNotification(xp) {
  // Small XP notification could be added here if needed
}

function applyTheme(theme) {
  document.body.setAttribute('data-theme', theme);
  // Apply to html element as well for better coverage
  document.documentElement.setAttribute('data-theme', theme);
}

// Background Noise Functions
async function initializeBackgroundNoise() {
  // Restore playing state if any
  const noiseSettings = await StorageManager.getNoiseSettings();
  if (noiseSettings && noiseSettings.playing) {
    setTimeout(() => {
      toggleNoise(noiseSettings.playing);
    }, 100);
  }
}

async function toggleNoise(soundType) {
  if (!audioContext) {
    audioContext = new (AudioContext || webkitAudioContext)();
  }
  
  // Resume audio context if suspended (browser autoplay policy)
  if (audioContext.state === 'suspended') {
    await audioContext.resume();
  }
  
  if (currentNoise === soundType) {
    // Stop current noise
    await stopNoise();
  } else {
    // Stop any playing noise and start new one
    await stopNoise();
    await playNoise(soundType);
  }
}

async function playNoise(soundType) {
  if (!audioContext) return;
  
  currentNoise = soundType;
  noiseNodes = [];
  
  // Create gain node for volume control
  const gainNode = audioContext.createGain();
  gainNode.gain.value = noiseVolume;
  gainNode.connect(audioContext.destination);
  
  switch(soundType) {
    case 'rain':
      createRainSound(gainNode);
      break;
    case 'ocean':
      createOceanSound(gainNode);
      break;
    case 'forest':
      createForestSound(gainNode);
      break;
    case 'fireplace':
      createFireplaceSound(gainNode);
      break;
    case 'white-noise':
      createWhiteNoise(gainNode);
      break;
    case 'wind':
      createWindSound(gainNode);
      break;
    case 'cafe':
      createCafeSound(gainNode);
      break;
    case 'thunder':
      createThunderSound(gainNode);
      break;
  }
  
  // Update UI
  updateNoiseUI(soundType, true);
  
  // Save state
  await StorageManager.updateNoiseSettings({ playing: soundType, volume: noiseVolume });
}

async function stopNoise() {
  // Clear all intervals
  noiseIntervals.forEach(intervalId => clearInterval(intervalId));
  noiseIntervals = [];
  
  noiseNodes.forEach(node => {
    if (node.oscillator) {
      node.oscillator.stop();
      node.oscillator.disconnect();
    }
    if (node.gain) {
      node.gain.disconnect();
    }
    if (node.bufferSource) {
      node.bufferSource.stop();
      node.bufferSource.disconnect();
    }
    if (node.lfo) {
      node.lfo.stop();
      node.lfo.disconnect();
    }
  });
  noiseNodes = [];
  
  if (currentNoise) {
    updateNoiseUI(currentNoise, false);
  }
  
  currentNoise = null;
  await StorageManager.updateNoiseSettings({ playing: null });
}

function updateNoiseVolume() {
  noiseNodes.forEach(node => {
    if (node.gain) {
      node.gain.gain.value = noiseVolume;
    }
  });
}

function updateNoiseUI(soundType, isPlaying) {
  const card = document.querySelector(`[data-sound="${soundType}"]`);
  if (!card) return;
  
  const btn = card.querySelector('.noise-play-btn');
  const playIcon = btn.querySelector('.play-icon');
  const pauseIcon = btn.querySelector('.pause-icon');
  
  if (isPlaying) {
    card.classList.add('playing');
    playIcon.style.display = 'none';
    pauseIcon.style.display = 'inline';
  } else {
    card.classList.remove('playing');
    playIcon.style.display = 'inline';
    pauseIcon.style.display = 'none';
  }
}

// Sound generation functions
function createRainSound(gainNode) {
  // Brown noise with filtering for rain effect
  const bufferSize = 4096;
  const buffer = audioContext.createBuffer(1, bufferSize, audioContext.sampleRate);
  const data = buffer.getChannelData(0);
  
  let lastOut = 0;
  for (let i = 0; i < bufferSize; i++) {
    const white = Math.random() * 2 - 1;
    const brown = (lastOut + (0.02 * white)) / 1.02;
    lastOut = brown;
    data[i] = brown * 3.5;
  }
  
  const source = audioContext.createBufferSource();
  source.buffer = buffer;
  source.loop = true;
  
  const filter = audioContext.createBiquadFilter();
  filter.type = 'lowpass';
  filter.frequency.value = 1000;
  filter.Q.value = 1;
  
  source.connect(filter);
  filter.connect(gainNode);
  source.start(0);
  
  noiseNodes.push({ bufferSource: source, gain: gainNode });
}

function createOceanSound(gainNode) {
  // Multiple oscillators for wave effect
  const oscillators = [];
  
  for (let i = 0; i < 3; i++) {
    const oscillator = audioContext.createOscillator();
    const gain = audioContext.createGain();
    const filter = audioContext.createBiquadFilter();
    
    oscillator.type = 'sawtooth';
    oscillator.frequency.value = 60 + (i * 20);
    
    filter.type = 'lowpass';
    filter.frequency.value = 800;
    
    gain.gain.value = 0.1;
    
    oscillator.connect(filter);
    filter.connect(gain);
    gain.connect(gainNode);
    
    // LFO for wave effect
    const lfo = audioContext.createOscillator();
    const lfoGain = audioContext.createGain();
    lfo.frequency.value = 0.1 + (i * 0.05);
    lfoGain.gain.value = 10;
    lfo.connect(lfoGain);
    lfoGain.connect(oscillator.frequency);
    
    oscillator.start(0);
    lfo.start(0);
    
    oscillators.push({ oscillator, gain, lfo });
  }
  
  noiseNodes.push(...oscillators.map(o => ({ oscillator: o.oscillator, gain: o.gain, lfo: o.lfo })));
}

function createForestSound(gainNode) {
  // Combination of bird-like tones and wind
  const oscillators = [];
  
  // Wind base
  const windOsc = audioContext.createOscillator();
  const windGain = audioContext.createGain();
  const windFilter = audioContext.createBiquadFilter();
  
  windOsc.type = 'sawtooth';
  windOsc.frequency.value = 100;
  windFilter.type = 'lowpass';
  windFilter.frequency.value = 500;
  windGain.gain.value = 0.15;
  
  windOsc.connect(windFilter);
  windFilter.connect(windGain);
  windGain.connect(gainNode);
  windOsc.start(0);
  
  oscillators.push({ oscillator: windOsc, gain: windGain });
  
  // Bird-like chirps (periodic)
  const chirpInterval = setInterval(() => {
    if (currentNoise === 'forest') {
      const chirp = audioContext.createOscillator();
      const chirpGain = audioContext.createGain();
      const chirpFilter = audioContext.createBiquadFilter();
      
      chirp.type = 'sine';
      chirp.frequency.setValueAtTime(800, audioContext.currentTime);
      chirp.frequency.exponentialRampToValueAtTime(1200, audioContext.currentTime + 0.1);
      
      chirpFilter.type = 'bandpass';
      chirpFilter.frequency.value = 1000;
      chirpFilter.Q.value = 10;
      
      chirpGain.gain.setValueAtTime(0.05, audioContext.currentTime);
      chirpGain.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.2);
      
      chirp.connect(chirpFilter);
      chirpFilter.connect(chirpGain);
      chirpGain.connect(gainNode);
      
      chirp.start();
      chirp.stop(audioContext.currentTime + 0.2);
    }
  }, 3000);
  noiseIntervals.push(chirpInterval);
  
  noiseNodes.push(...oscillators);
}

function createFireplaceSound(gainNode) {
  // Crackling fire effect using filtered noise
  const bufferSize = 4096;
  const buffer = audioContext.createBuffer(1, bufferSize, audioContext.sampleRate);
  const data = buffer.getChannelData(0);
  
  for (let i = 0; i < bufferSize; i++) {
    data[i] = Math.random() * 2 - 1;
  }
  
  const source = audioContext.createBufferSource();
  source.buffer = buffer;
  source.loop = true;
  
  const filter = audioContext.createBiquadFilter();
  filter.type = 'bandpass';
  filter.frequency.value = 2000;
  filter.Q.value = 2;
  
  source.connect(filter);
  filter.connect(gainNode);
  source.start(0);
  
  noiseNodes.push({ bufferSource: source, gain: gainNode });
  
  // Periodic crackling pops
  const popInterval = setInterval(() => {
    if (currentNoise === 'fireplace') {
      const pop = audioContext.createOscillator();
      const popGain = audioContext.createGain();
      
      pop.type = 'sine';
      pop.frequency.value = 100;
      
      popGain.gain.setValueAtTime(0.1, audioContext.currentTime);
      popGain.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.05);
      
      pop.connect(popGain);
      popGain.connect(gainNode);
      
      pop.start();
      pop.stop(audioContext.currentTime + 0.05);
    }
  }, 2000);
  noiseIntervals.push(popInterval);
}

function createWhiteNoise(gainNode) {
  const bufferSize = 4096;
  const buffer = audioContext.createBuffer(1, bufferSize, audioContext.sampleRate);
  const data = buffer.getChannelData(0);
  
  for (let i = 0; i < bufferSize; i++) {
    data[i] = Math.random() * 2 - 1;
  }
  
  const source = audioContext.createBufferSource();
  source.buffer = buffer;
  source.loop = true;
  
  const filter = audioContext.createBiquadFilter();
  filter.type = 'lowpass';
  filter.frequency.value = 5000;
  
  source.connect(filter);
  filter.connect(gainNode);
  source.start(0);
  
  noiseNodes.push({ bufferSource: source, gain: gainNode });
}

function createWindSound(gainNode) {
  // Low frequency filtered noise
  const bufferSize = 4096;
  const buffer = audioContext.createBuffer(1, bufferSize, audioContext.sampleRate);
  const data = buffer.getChannelData(0);
  
  for (let i = 0; i < bufferSize; i++) {
    data[i] = Math.random() * 2 - 1;
  }
  
  const source = audioContext.createBufferSource();
  source.buffer = buffer;
  source.loop = true;
  
  const filter = audioContext.createBiquadFilter();
  filter.type = 'lowpass';
  filter.frequency.value = 200;
  filter.Q.value = 1;
  
  source.connect(filter);
  filter.connect(gainNode);
  source.start(0);
  
  noiseNodes.push({ bufferSource: source, gain: gainNode });
}

function createCafeSound(gainNode) {
  // Multiple oscillators for ambient chatter effect
  const oscillators = [];
  
  for (let i = 0; i < 5; i++) {
    const oscillator = audioContext.createOscillator();
    const gain = audioContext.createGain();
    const filter = audioContext.createBiquadFilter();
    
    oscillator.type = 'sawtooth';
    oscillator.frequency.value = 200 + (i * 50);
    
    filter.type = 'lowpass';
    filter.frequency.value = 1000;
    
    gain.gain.value = 0.05;
    
    oscillator.connect(filter);
    filter.connect(gain);
    gain.connect(gainNode);
    
    // Random frequency modulation
    const lfo = audioContext.createOscillator();
    const lfoGain = audioContext.createGain();
    lfo.frequency.value = 0.5 + Math.random();
    lfoGain.gain.value = 20;
    lfo.connect(lfoGain);
    lfoGain.connect(oscillator.frequency);
    
    oscillator.start(0);
    lfo.start(0);
    
    oscillators.push({ oscillator, gain, lfo });
  }
  
  noiseNodes.push(...oscillators.map(o => ({ oscillator: o.oscillator, gain: o.gain })));
}

function createThunderSound(gainNode) {
  // Low rumbling with occasional thunder claps
  const rumble = audioContext.createOscillator();
  const rumbleGain = audioContext.createGain();
  const rumbleFilter = audioContext.createBiquadFilter();
  
  rumble.type = 'sawtooth';
  rumble.frequency.value = 40;
  
  rumbleFilter.type = 'lowpass';
  rumbleFilter.frequency.value = 300;
  
  rumbleGain.gain.value = 0.2;
  
  rumble.connect(rumbleFilter);
  rumbleFilter.connect(rumbleGain);
  rumbleGain.connect(gainNode);
  rumble.start(0);
  
  noiseNodes.push({ oscillator: rumble, gain: rumbleGain });
  
  // Periodic thunder claps
  const thunderInterval = setInterval(() => {
    if (currentNoise === 'thunder') {
      const clap = audioContext.createOscillator();
      const clapGain = audioContext.createGain();
      
      clap.type = 'sawtooth';
      clap.frequency.setValueAtTime(100, audioContext.currentTime);
      clap.frequency.exponentialRampToValueAtTime(50, audioContext.currentTime + 0.3);
      
      clapGain.gain.setValueAtTime(0.3, audioContext.currentTime);
      clapGain.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.5);
      
      clap.connect(clapGain);
      clapGain.connect(gainNode);
      
      clap.start();
      clap.stop(audioContext.currentTime + 0.5);
    }
  }, 8000);
  noiseIntervals.push(thunderInterval);
}

